/**
 * 初始化部门详情对话框
 */
var IsDealInfoDlg = {
    isDealInfoData: {},
    zTreeInstance: null,
    validateFields: {}
};

/**
 * 清除数据
 */
IsDealInfoDlg.clearData = function () {
    this.isDealInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
IsDealInfoDlg.set = function (key, val) {
    this.isDealInfoData[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
IsDealInfoDlg.get = function (key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
IsDealInfoDlg.close = function () {
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    parent.layer.close(index);
}

/**
 * 显示部门选择的树
 *
 * @returns
 */
IsDealInfoDlg.showIsDealSelectTree = function () {
    var pName = $("#pName");
    var pNameOffset = $("#pName").offset();
    $("#parentIsDealMenu").css({
        left: pNameOffset.left + "px",
        top: pNameOffset.top + pName.outerHeight() + "px"
    }).slideDown("fast");

    $("body").bind("mousedown", onBodyDown);
}

/**
 * 隐藏部门选择的树
 */
IsDealInfoDlg.hideIsDealSelectTree = function () {
    $("#parentIsDealMenu").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);// mousedown当鼠标按下就可以触发，不用弹起
}

IsDealInfoDlg.resetSearch = function () {
    $("#payServiceNames").val("");
    $("#payServicePrices").val("");
    IsDealInfoDlg.search();
}
IsDealInfoDlg.search = function () {
    var payServiceNames = document.getElementById("payServiceNames").value;
    var payServicePrices = document.getElementById("payServicePrices").value;
    var customerId = document.getElementById("customerId").value;
    var reservationsId = document.getElementById("reservationsId").value;
    var npcr = payServiceNames + "," + payServicePrices + "," + customerId + "," + reservationsId;
    var index = layer.open({
        type: 2,
        title: '收费项目搜索',
        area: ['90%', '90%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/payService/to_getPayServiceLists/' + npcr
    });
    this.layerIndex = index;
}


/**
 * 收集数据
 */
IsDealInfoDlg.collectData = function () {
    this.set('reservationsId').set('consumptionStatus').set('followStatus').set('appointmentTime').set('arrearsRemarks')
        .set('arrears').set('serviceActualPay').set('doctor').set('nurse').set('customerId').set('operationTime')
        .set('noDealCause').set('appointmentTimes').set('toVoidCause').set('payServiceId').set('reservationss')
        .set('payServiceNum').set('remarkss').set('reservations').set('followStatuss').set('consumptionStatuss').set('remarks');
}

/**
 * 验证数据是否为空
 */
IsDealInfoDlg.validate = function () {
    $('#isDealInfoForm').data("bootstrapValidator").resetForm();
    $('#isDealInfoForm').bootstrapValidator('validate');
    return $("#isDealInfoForm").data('bootstrapValidator').isValid();
}

function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "parentIsDealMenu" || $(
            event.target).parents("#parentIsDealMenu").length > 0)) {
        IsDealInfoDlg.hideIsDealSelectTree();
    }
}

/**
 * 添加不成交记录
 */
IsDealInfoDlg.addNoDeal = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    if (document.getElementById("department").value == null || document.getElementById("department").value == "") {
        alert("请选择科室");
        return;
    }
    if (document.getElementById("firstLevelProject").value == null || document.getElementById("firstLevelProject").value == "") {
        alert("请选择一级项目");
        return;
    }
    if (document.getElementById("noDealCause").value == null || document.getElementById("noDealCause").value == "") {
        alert("请输入不成交原因");
        return;
    }
    if (document.getElementById("appointmentTimes").value == null || document.getElementById("appointmentTimes").value == "") {
        alert("请输入回访时间");
        return;
    }
    if ($('#noDealCause').length > 15000) {
        alert("不成交原因长度小于1万5");
        return;
    }
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/consultant/add_isNoDeal", function (data) {
        Feng.success("操作成功!");
        window.parent.Consultant.table.refresh();
        IsDealInfoDlg.close();
    }, function () {
        Feng.error("操作失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.isDealInfoData);
    ajax.start();
}

/**
 * 添加不成交记录
 */
IsDealInfoDlg.addToVoid = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    if (document.getElementById("toVoidCause").value == null || document.getElementById("toVoidCause").value == "") {
        alert("请输入作废原因");
        return;
    }
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/consultant/add_isToVoid", function (data) {
        Feng.success("操作成功!");
        window.parent.parent.Consultant.table.refresh();
        // IsDealInfoDlg.close();
        $('#cancel', parent.document).click();
    }, function () {
        Feng.error("操作失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.isDealInfoData);
    ajax.start();
}

IsDealInfoDlg.cancelBill = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/payService/cancelBill", function (data) {
        Feng.success("操作成功!");
        window.parent.Consultant.table.refresh();
        IsDealInfoDlg.close();
    }, function () {
        Feng.error("操作失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.isDealInfoData);
    ajax.start();
}

IsDealInfoDlg.distributiveDoctor = function () {
    var customerId = document.getElementById("customerId").value;
    var index = layer.open({
        type: 2,
        title: '分配医生',
        area: ['90%', '90%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/consultant/to_distributiveDoctor/' + customerId
    });
    this.layerIndex = index;
}
var getCount = 0;
/**
 * 开单
 */
IsDealInfoDlg.openBill = function () {
    getCount++;
    if (getCount == 1) {
        this.clearData();
        this.collectData();
        if (!this.validate()) {
            return;
        }
        //通过CLASS获取服务项目数组和实付金额数组以及折后金额
        var serverIdInpus = document.getElementsByClassName("serviceId");
        var totleinputs = document.getElementsByClassName("totleinput");
        var ids = document.getElementsByClassName("serviceIds");
        var totalzhe = document.getElementsByClassName("totalzhe");
        var itemsParam = "";//把多个项目的ID和实付金额拼接成字符串, （项目ID，项目实付金额|项目ID，项目实付金额....)
        for (var tempIndex = 0; tempIndex < serverIdInpus.length; tempIndex++) {
            var currentServiceId = serverIdInpus[tempIndex].value;//jquery .val() 前提必须是标签通过JQUERY获取  $("#id").val()
            var currentServiceTotal = totleinputs[tempIndex].value;
            var serviceIds = ids[tempIndex].value;
            var currentZheTotal = totalzhe[tempIndex].innerText;//juqery .text()/.html() 前提必须是标签通过JQUERY获取  $("#id").text()
            itemsParam = itemsParam + currentServiceId + "," + currentServiceTotal + "," + currentZheTotal +"," + serviceIds + "|";
        }
        this.isDealInfoData["itemsParam"] = itemsParam;//各个项目实付金额字符串
        //alert(itemsParam);

        var doctor = document.getElementById("doctor").value;
        // var nurse = document.getElementById("nurse").value;
        //折后金额
        var totleFoldingPays = document.getElementById("totleFoldingPays").value;
        //实付金额
        var serviceActualPay = document.getElementById("serviceActualPay").value;
        //备注
        var remarkss = document.getElementById("remarkss").value;
        var customerId = document.getElementById("customerId").value;
        var reservationsId = document.getElementById("reservationsId").value;
        var arrearsRemarks = $("#arrearsRemarks").val();
        var arrears = parseFloat(totleFoldingPays) - parseFloat(serviceActualPay);
        this.isDealInfoData["serviceActualPay"] = serviceActualPay;
        this.isDealInfoData["remarkss"] = remarkss;
        // var checkValue = document.getElementsByName("checkValue");
        //  for(var i=0;i<radio_tag.length;i++){
        //     if(radio_tag[i].checked){
        //         var checcheckValueue = radio_tag[i].value;
        //         break;
        //     }
        // }
        //  this.isDealInfoData["checkValue"] = checkValue;
        //比较折后金额和实付金额，如果折后金额比实付金额大，证明没有付完全费用，走欠费逻辑
        if (parseFloat(totleFoldingPays) > parseFloat(serviceActualPay)) {

            if (arrearsRemarks == null || arrearsRemarks == "") {
                getCount = 0;
                var cras = customerId + "," + reservationsId + "," + arrears + "," + serviceActualPay;
                var index = layer.open({
                    type: 2,
                    title: '欠款备注',
                    area: ['90%', '90%'], //宽高
                    fix: true, //不固定
                    maxmin: true,
                    content: Feng.ctxPath + '/consultant/to_arrearsRemarks/' + cras
                });
                this.layerIndex = index;
            } else {
                //提交信息
                var ajax = new $ax(Feng.ctxPath + "/consultant/openBill", function (data) {
                    var index = layer.open({
                        type: 2,
                        title: '开单打印',
                        area: ['60%', '100%'], //宽高
                        fix: true, //不固定
                        maxmin: true,
                        content: Feng.ctxPath + '/consultant/singlePrint/' + customerId,
                        success:function () {
                            window.parent.Consultant.table.refresh();
                        }
                    });
                    this.layerIndex = index;
                }, function () {
                    Feng.error("操作失败!" + data.responseJSON.message + "!");
                });
                ajax.set(this.isDealInfoData);
                ajax.start();
            }
        } else if (parseFloat(totleFoldingPays) == parseFloat(serviceActualPay)) {//如果折后金额和实付金额一致，证明已经付款完整
            //提交信息
            var ajax = new $ax(Feng.ctxPath + "/consultant/openBill", function (data) {
                var index = layer.open({
                    type: 2,
                    title: '开单打印',
                    area: ['60%', '100%'], //宽高
                    fix: true, //不固定
                    maxmin: true,
                    content: Feng.ctxPath + '/consultant/singlePrint/' + customerId,
                    success:function () {
                        window.parent.Consultant.table.refresh();
                    }
                });
                this.layerIndex = index;
            }, function () {
                Feng.error("操作失败!" + data.responseJSON.message + "!");
            });
            ajax.set(this.isDealInfoData);
            ajax.start();
        } else {
            alert("实际付款不应大于折后价！");
            return;
        }
    }
};


IsDealInfoDlg.openBills = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    var doctor = document.getElementById("doctor").value;
    //折后金额
    var totleFoldingPays = document.getElementById("totleFoldingPays").value;
    //实付金额
    var serviceActualPay = document.getElementById("serviceActualPay").value;
    //通过CLASS获取服务项目数组和实付金额数组
    var serverIdInpus = document.getElementsByClassName("serviceId");
    var totleinputs = document.getElementsByClassName("totleinput");
    var ids = document.getElementsByClassName("serviceIds");
    var totalzhe = document.getElementsByClassName("totalzhe");
    var itemsParam = "";//把多个项目的ID和实付金额拼接成字符串, （项目ID，项目实付金额|项目ID，项目实付金额....)
    for (var tempIndex = 0; tempIndex < serverIdInpus.length; tempIndex++) {
        var currentServiceId = serverIdInpus[tempIndex].value;
        var currentServiceTotal = totleinputs[tempIndex].value;
        var serviceIds=ids[tempIndex].value;
        var currentZheTotal = totalzhe[tempIndex].innerText;//juqery .text()/.html() 前提必须是标签通过JQUERY获取  $("#id").text()
        itemsParam = itemsParam + currentServiceId + "," + currentServiceTotal + "," + currentZheTotal +"," + serviceIds + "|";
    }
    //alert(itemsParam);
    this.isDealInfoData["itemsParam"] = itemsParam;//各个项目实付金额字符串
    var customerId = document.getElementById("customerId").value;
    var reservationsId = document.getElementById("reservationsId").value;
    var arrearsRemarks = $("#arrearsRemarks").val();
    var arrears = parseFloat(totleFoldingPays) - parseFloat(serviceActualPay);
    this.isDealInfoData["serviceActualPay"] = serviceActualPay;
    if (parseFloat(totleFoldingPays) > parseFloat(serviceActualPay)) {
        if (arrearsRemarks == null || arrearsRemarks == "") {
            var cras = customerId + "," + reservationsId + "," + arrears + "," + serviceActualPay;
            var index = layer.open({
                type: 2,
                title: '欠款备注',
                area: ['90%', '90%'], //宽高
                fix: true, //不固定
                maxmin: true,
                content: Feng.ctxPath + '/consultant/to_arrearsRemarks/' + cras
            });
            this.layerIndex = index;
        } else {
            //提交信息
            var ajax = new $ax(Feng.ctxPath + "/consultant/openBill", function (data) {
                Feng.success("操作成功!");
                window.parent.parent.Consultant.table.refresh();
                IsDealInfoDlg.close();
            }, function () {
                Feng.error("操作失败!" + data.responseJSON.message + "!");
            });
            ajax.set(this.isDealInfoData);
            ajax.start();
        }
    } else if (parseFloat(totleFoldingPays) == parseFloat(serviceActualPay)) {//如果折后金额和实付金额一致，证明已经付款完整
        //提交信息
        var ajax = new $ax(Feng.ctxPath + "/consultant/openBill", function (data) {
            Feng.success("操作成功!");
            window.parent.parent.Consultant.table.refresh();
            IsDealInfoDlg.close();
        }, function () {
            Feng.error("操作失败!" + data.responseJSON.message + "!");
        });
        ajax.set(this.isDealInfoData);
        ajax.start();
    } else {
        alert("实际付款不应大于折后价！");
        return
    }
}

IsDealInfoDlg.addArrearsRemarks = function () {
    var arrearsRemarks = $("#arrearsRemarks").val();
    if (arrearsRemarks == "" || arrearsRemarks == null) {
        alert("请输入欠款备注");
        return;
    }
    var arrears = $("#arrears").val();
    var serviceActualPays = $("#serviceActualPays").val();
    window.parent.document.getElementById("serviceActualPay").value = serviceActualPays;
    window.parent.document.getElementById("arrearsRemarks").value = arrearsRemarks;
    window.parent.document.getElementById("arrears").value = arrears;
    window.parent.document.getElementById("arrearsOfMoney").innerHTML += '<p style="margin-top: 10px;">欠款：' + arrears + '元<div>'
    window.parent.document.getElementById("arrearsOfMoney").innerHTML += '<p>欠款备注：' + arrearsRemarks + '' +
        ' <a href=\"javascript:;\" onclick=\"IsDealInfoDlg.openBills()\">&nbsp修改备注</a><div>';
    Feng.success("添加欠款备注成功!");
    IsDealInfoDlg.close();
}

/**
 * 成交
 */
IsDealInfoDlg.openBills = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    var doctor = document.getElementById("doctor").value;
    var totleFoldingPays = document.getElementById("totleFoldingPays").value;
    var serviceActualPay = document.getElementById("serviceActualPay").value;
    var customerId = document.getElementById("customerId").value;
    var reservationsId = document.getElementById("reservationsId").value;
    var arrearsRemarks = $("#arrearsRemarks").val();
    var arrears = parseFloat(totleFoldingPays) - parseFloat(serviceActualPay);
    if (doctor == null || doctor == "") {
        alert("请分配医生！");
        return
    }
    var cras = customerId + "," + reservationsId + "," + arrears + "," + serviceActualPay;
    var index = layer.open({
        type: 2,
        title: '欠款备注',
        area: ['90%', '90%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/consultant/to_arrearsRemarks/' + cras
    });
    this.layerIndex = index;
};

IsDealInfoDlg.initData = function () {
    //状态单选
    var seletecustomerSex = $('#customerSexValue').val();
    if ($('#id').val() != "") {
        $("#customerSex option[value=" + seletecustomerSex + "]").attr("selected", "selected");
    }
    if ($('#id').val() != "") {
        $("#select1 option[value=" + seletecustomerSex + "]").attr("selected", "selected");
    }
}

$(function () {
    Feng.initValidator("isDealInfoForm", IsDealInfoDlg.validateFields);
    IsDealInfoDlg.initData();
    var radios = document.getElementsByName('radio');
    for (var i = 0; i < radios.length; i++) {
        radios[i].indexs = i + 1;
        radios[i].onchange = function () {
            document.getElementById('url1').value = '';
            if (this.checked) {
                document.getElementById("url2").style.display = "none";
                document.getElementById("url1").style.display = "none";
                document.getElementById('url1').selectedIndex = "";
                document.getElementById('url2').value = '';
                document.getElementById("url" + this.indexs).style.display = "block";
            }
        }
    }
    ;
});
